package com.samsung.sbackup;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

import net.lingala.zip4j.exception.ZipException;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.samsung.adapter.FileAdapter;
import com.samsung.handler.ZipHandler;
import com.samsung.item.FileItem;

public class FragmentManageBackups extends Fragment {

	Button btnInternal, btnExternal, btnDelete;
	FileAdapter adapterInternal, adapterExternal;
	ListView lvFiles;
	TextView tvPath;

	boolean isExternalChecked;
	String internalPath;
	String externalPath;

	public FragmentManageBackups() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setHasOptionsMenu(true);
		String storage[] = FragmentSettingsPreference.getStorageDirectories();
		if (storage[0] != null || storage[1] != null) {
			externalPath = String.valueOf(storage[0]);
			internalPath = String.valueOf(storage[1]);
		} else {
			externalPath = "Not available";
			internalPath = "Not available";
		}
		isExternalChecked = false;
		if (new File(externalPath).list() != null) {
			internalPath += "/Android/data/" + getActivity().getPackageName()
					+ "/files/Download";
			externalPath += "/Android/data/" + getActivity().getPackageName()
					+ "/files/Download";
		} else {
			internalPath += "/Android/data/" + getActivity().getPackageName()
					+ "/files/Download";
			externalPath = "Not inserted";
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.manage_backups, container, false);
		btnInternal = (Button) view
				.findViewById(R.id.frag_manage_backups_btnInternalStorage);
		btnExternal = (Button) view
				.findViewById(R.id.frag_manage_backups_btnExternalStorage);
		btnDelete = (Button) view
				.findViewById(R.id.frag_manage_backups_btnDelete);

		lvFiles = (ListView) view
				.findViewById(R.id.frag_manage_backups_listview);
		adapterInternal = new FileAdapter(getActivity(),
				R.layout.manage_backups_item, new ArrayList<FileItem>());
		adapterExternal = new FileAdapter(getActivity(),
				R.layout.manage_backups_item, new ArrayList<FileItem>());
		lvFiles.setAdapter(adapterInternal);
		tvPath = (TextView) view.findViewById(R.id.frag_manage_backups_tvPath);

		btnInternal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				isExternalChecked = false;
				adapterInternal.clear();
				btnInternal
						.setBackgroundResource(R.drawable.block_arcbg_checked);
				btnExternal.setBackgroundResource(R.drawable.block_selector);
				tvPath.setText(internalPath);

				File[] fs = new File(internalPath).listFiles();

				if (internalPath.equals("Not available"))
					Toast.makeText(getActivity(),
							"Internal storage not available", Toast.LENGTH_LONG)
							.show();
				else if (fs == null || fs.length == 0) {
					Toast.makeText(getActivity(),
							"There is no backups in Internal Storage",
							Toast.LENGTH_LONG).show();
				} else {
					ArrayList<File> files = new ArrayList<File>();
					for (File f : fs) {
						if (!f.getName().contains("zip"))
							f.delete();
						else
							files.add(f);
					}
					Collections.sort(files, new QuickBackup.NameComparator());

					for (int i = 0; i < files.size(); i++) {
						System.out.println(files.get(i).getName());
						boolean fileHasPass = false;
						try {
							fileHasPass = ZipHandler.isPassword(internalPath
									+ "/" + files.get(i).getName());
						} catch (ZipException e) {
							e.printStackTrace();
						}

						adapterInternal.addItem(new FileItem(files.get(i)
								.getName(), false, fileHasPass));
					}
				}
				lvFiles.setAdapter(adapterInternal);
			}
		});

		// display backups in Internal Storage the first time fragment is
		// created
		btnInternal.performClick();

		btnExternal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				isExternalChecked = true;
				adapterExternal.clear();
				btnExternal
						.setBackgroundResource(R.drawable.block_arcbg_checked);
				btnInternal.setBackgroundResource(R.drawable.block_selector);
				tvPath.setText(externalPath);

				File[] fs = new File(externalPath).listFiles();

				if (externalPath.equals("Not available"))
					Toast.makeText(getActivity(),
							"External storage not available", Toast.LENGTH_LONG)
							.show();
				else if (fs == null || fs.length == 0) {
					Toast.makeText(getActivity(),
							"There is no backups in External Storage",
							Toast.LENGTH_LONG).show();
				} else {
					ArrayList<File> files = new ArrayList<File>();
					for (File f : fs) {
						if (!f.getName().contains("zip"))
							f.delete();
						else
							files.add(f);
					}
					Collections.sort(files, new QuickBackup.NameComparator());

					for (int i = 0; i < files.size(); i++) {
						System.out.println(files.get(i).getName());
						boolean fileHasPass = false;
						try {
							fileHasPass = ZipHandler.isPassword(externalPath
									+ "/" + files.get(i).getName());
						} catch (ZipException e) {
							e.printStackTrace();
						}

						adapterExternal.addItem(new FileItem(files.get(i)
								.getName(), false, fileHasPass));
					}
				}
				lvFiles.setAdapter(adapterExternal);
			}
		});

		btnDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int count = 0;
				if (isExternalChecked) {
					for (FileItem file : adapterExternal.getAllItems()) {
						if (file.isChecked()) {
							File f = new File(externalPath + "/"
									+ file.getFileName());
							if (f.delete())
								count++;
						}
					}
					Toast.makeText(getActivity(),
							"Deleted " + String.valueOf(count) + " file(s)",
							Toast.LENGTH_LONG).show();
					btnExternal.performClick();
				} else {
					for (FileItem file : adapterInternal.getAllItems()) {
						if (file.isChecked()) {
							File f = new File(internalPath + "/"
									+ file.getFileName());
							if (f.delete())
								count++;
						}
					}
					Toast.makeText(getActivity(),
							"Deleted " + String.valueOf(count) + " file(s)",
							Toast.LENGTH_LONG).show();
					btnInternal.performClick();
				}
			}
		});
		return view;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.main, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

}
